package cn.stylefeng.guns.modular.ws.sso.action;

import cn.stylefeng.guns.base.auth.jwt.JwtTokenUtil;
import cn.stylefeng.guns.base.auth.jwt.payload.JwtPayLoad;
import cn.stylefeng.guns.base.auth.model.LoginUser;
import cn.stylefeng.guns.sys.core.auth.cache.SessionManager;
import cn.stylefeng.guns.sys.core.auth.cache.impl.DefaultSessionManager;
import cn.stylefeng.guns.sys.core.log.LogManager;
import cn.stylefeng.guns.sys.core.log.factory.LogTaskFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import static cn.stylefeng.roses.core.util.HttpContext.getIp;

/**
 * @Author:
 * @Date: 2019/1/9 11:12
 */
public class HttpUrlConnectionTest {

    /**
     * header 在传输header时请务必加上charset=utf-8;
     *  "Content-Type: application/x-www-form-urlencoded;charset=utf-8\n"
     */
    public static final String HEADER =
            "Accept-Encoding: gzip,deflate\n" +
                    "Content-Type: application/x-www-form-urlencoded;charset=utf-8\n" +
                    "Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMzE1NjI4OTEyMzY1MTk5MzYxIiwiZXhwIjoxNjAyOTE1Mjk0LCJ1c2VySWQiOjEzMTU2Mjg5MTIzNjUxOTkzNjEsImlhdCI6MTYwMjgyODg5NCwiYWNjb3VudCI6ImZlbmd0eSIsInVzZXJLZXkiOiJ4eHh4In0.i_f2oQKgL4qpkNML-KQZUnbPz8ULa8oOoy7ZtiYQdwnd0y31RKmkNs9IjgXQ-VpwCbDkxpxBHMU3WCRNNUF1Sw\n" +
                    "Connection: Keep-Alive";

    public static void main(String[] args) throws Exception {
        //String url = "http://127.0.0.1/rest/login?username=admin&password=111111";
        String url = "http://127.0.0.1/rest/mgr/list" ;
        Map<String, String> header =splid(HEADER);
        //String h = JSON.toJSONString(header);
        //System.out.println(h);
        //Map<String, Object> map = new HashMap<String, Object>();
        //JSONObject ob =new  JSONObject();
        //ob.put("username","admin") ;
        //ob.put("password","111111") ;
        //String postDataJson = JSON.toJSONString(ob);
        //System.out.println(postDataJson);

        String json = "{\"username\":\"admin\",\"password\":\"111111\"}";
        System.out.println(json);
        String result = sendPost(url,"",header);
        System.out.println(result) ;


        //TODO key的作用
    /*   JwtPayLoad payLoad = new JwtPayLoad(new Long(1), "admin", "Authorization");

        //创建token
        String token = JwtTokenUtil.generateToken(payLoad);
        System.out.println("token:"+token);*/


      /*  SessionManager sm = new DefaultSessionManager() ;
        LoginUser user = new LoginUser();
        user.setId(new Long(1));
        user.setAccount("admin");
        sm.createSession(token,user); ;
        LoginUser u = sm.getSession(token) ;
        System.out.println(u.getName()) ;*/
        //创建登录会话
        /*sessionManager.createSession(token, user(username));

        //创建cookie
        addLoginCookie(token);

        return token;*/

    }
    /**
     * @param url 访问地址
     *  @param param 需要传输参数参数；对象可以通过json转换成String
     * @param header header 参数；可以通过下面工具类将string类型转换成map
     * @return 返回网页返回的数据
     */
    public static String sendPost(String url, String param, Map<String, String> header) throws  IOException, IOException {
        OutputStreamWriter out;
        BufferedReader in = null;
        String result = "";
        URL realUrl = new URL(url);
        // 打开和URL之间的连接
        HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
        //设置超时时间
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(15000);
        // 设置通用的请求属性
        if (header!=null) {
            for (Map.Entry<String, String> entry : header.entrySet()) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        conn.setRequestMethod("POST");
        conn.addRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        // 发送POST请求必须设置如下两行
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // 获取URLConnection对象对应的输出流
        out = new OutputStreamWriter( conn.getOutputStream(),"UTF-8");// utf-8编码
        // 发送请求参数
        out.write(param);

        // flush输出流的缓冲
        out.flush();
        // 定义BufferedReader输入流来读取URL的响应
        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf8"));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
        if(out!=null){
            out.close();
        }
        if(in!=null){
            in.close();
        }
        return result;
    }
    /**
     *Header字符串转map
     * @param zz
     * @return
     */
    public static Map<String, String> splid(String zz) {
        String[] stepOne = zz.split("\n");
        Map<String, String> map = new HashMap<String, String>();
        for (int i = 0; i < stepOne.length; i++) {
            String[] stepTwo = stepOne[i].split(": ");
            if (map.get(stepTwo[0]) == null) {
                map.put(stepTwo[0], stepTwo[1]);
            } else {
                map.put(stepTwo[0], stepTwo[1] + "," + map.get(stepTwo[0]));
            }
        }
        return map;
    }


}